/**
 * Copyright (c) 2022 Yansen Zhang
 * wxcomponent is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
**/

package request

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"

	wxerr "gitee.com/yansen_zh/wxcomponent/errors"
	"gitee.com/yansen_zh/wxcomponent/utils/log"
)

func post(url string, contentType string, body []byte) ([]byte, error) {

	logger := log.GetLogger()
	logger.Info("发送请求: ", url)

	if len(body) > 0 {
		logger.Info(body)
	}

	resp, e1 := http.Post(url, contentType, bytes.NewReader(body))
	if e1 != nil {
		return nil, e1
	}

	if resp.StatusCode > 299 {
		return nil, errors.New(resp.Status)
	}

	body, e2 := io.ReadAll(resp.Body)
	resp.Body.Close()
	if e2 != nil {
		return nil, e2
	}

	logger.Info("微信端返回: ", body)

	return body, nil
}

// PostJSON 使用 POST 方式发送 json 数据
func PostJSON(addr string, query *url.Values, body interface{}) ([]byte, error) {
	apiURL, e0 := ParseURL(addr, query)
	if e0 != nil {
		return nil, e0
	}

	data, e1 := json.Marshal(body)
	if e1 != nil {
		return nil, e1
	}

	resp, e2 := post(apiURL.String(), ContentTypeJSON, data)
	if e2 != nil {
		return nil, e2
	}

	e3 := wxerr.Error{}
	if err := json.Unmarshal(resp, &e3); err != nil {
		return nil, err
	}

	if e3.Code != 0 {
		return nil, e3
	}

	return resp, nil
}
